package model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class Author extends BaseModel {

	private long id;
	private String firstName;
	private String lastName;
	private Account account;
	private List<Work> works;
	private WorkSharedDB db;

	public Author(String firstName, String lastName, String username, String password) throws Exception {
		super();
		setFirstName(firstName);
		setLastName(lastName);
		this.account = new Account(username, password);
		this.db = new WorkSharedDB();
	}

	public Author(String username, String password) throws Exception {
		this.account = new Account(username, password);
		this.db = new WorkSharedDB();
		this.loadWith(username, password);
	}

	public Author(long id, String firstName, String lastName) throws Exception {
		super();
		setId(id);
		setFirstName(firstName);
		setLastName(lastName);
		this.db = new WorkSharedDB();
	}

	public void register() throws Exception {
		try {
			db.statement = WorkSharedDB.connection
					.prepareStatement("INSERT INTO authors(first_name, last_name, username, passhash) VALUES(?, ?, ?, ?)");
			db.statement.setString(1, getFirstName());
			db.statement.setString(2, getLastName());
			db.statement.setString(3, getUsername());
			db.statement.setString(4, account.getPassHash());

			db.statement.execute();
		} catch (SQLException ex) {
			if (ex.getMessage().toUpperCase().contains("ERROR 1062")) {
				throw new Exception("O username " + getUsername() + "já existe!");
			}
		}

	}

	private void loadWith(String username, String password) throws Exception {
		try {
			db.statement = WorkSharedDB.connection
					.prepareStatement("SELECT id, first_name, last_name, username FROM authors WHERE username = ? AND passhash = ? ");
			db.statement.setString(1, getUsername());
			db.statement.setString(2, account.getPassHash());

			ResultSet rs = db.statement.executeQuery();
			if (rs.next()) {
				setFirstName(rs.getString("first_name"));
				setLastName(rs.getString("last_name"));
				setId(rs.getLong("id"));
			}
		} catch (SQLException ex) {
			throw new Exception("Erro ao carregar autor por username e senha!");
		}

	}

	/* Gets and Sets */
	public long getId() {
		return id;
	}

	public List<Work> getWorks() {
		return works;
	}

	public void setId(long id) {
		this.id = id;
	}

	public void setWorks(List<Work> works) {
		this.works = works;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setFirstName(String firstName) throws Exception {
		doStringCheck(firstName, "Nome", 30);
		this.firstName = firstName;
	}

	public void setLastName(String lastName) throws Exception {
		doStringCheck(lastName, "Sobrenome", 80);
		this.lastName = lastName;
	}

	public String getUsername() {
		return account.getUsername();
	}

	public Account getAccount() {
		return account;
	}

}
